/**
 *  JSimProd - Java simulation code for production processes
 *  Copyleft Jorge Mira Yagüe <jorge.mira.yague@gmail.com>
 *  Universidad de Alicante 2009
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

/*
 * frmProductionPlan.java
 *
 * Created on 18-feb-2009, 18:36:44
 */
package gui.forms;

import gui.tools.Receiver;
import gui.tools.models.TMOrder;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.event.TableModelEvent;
import lib.model.FactoryModel;
import lib.plan.Order;
import lib.plan.ProductionPlan;

/**
 *
 * @author jorge
 */
public class FrmProductionPlan extends javax.swing.JDialog implements Receiver {

    private ProductionPlan plan;
    private FactoryModel factory;
    private Receiver parent;
    private boolean add;
    private int index;

    /** Creates new form frmProductionPlan */
    public FrmProductionPlan(ProductionPlan plan, FactoryModel factory, Receiver parent) {
        initComponents();

        this.getRootPane().setDefaultButton(btnSave);

        tbOrders.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2) {
                    btnOrdersModifyActionPerformed(null);
                }
            }
        });

        String fileString = "/res/icons/logo.png";
        try {
            java.awt.Image icon =
                    javax.imageio.ImageIO.read(new java.io.File(fileString));
            this.setIconImage(icon);
        } catch (java.io.IOException ioe) {
            System.out.println("Error loading file: " + fileString);
        }

        this.plan = plan;
        this.factory = factory;
        this.parent = parent;
        DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy-HH:mm");

        if (plan != null) {
            this.setTitle("Editing production plan :" + plan.getName());
            txtPPName.setText(plan.getName());
            txtWhenModified.setText(formatter.format(plan.getWhenModified().getTime()));
            tbOrders.setModel(new TMOrder(plan.getOrders()));
        } else {
            this.setTitle("New production plan:");
            tbOrders.setModel(new TMOrder(new ArrayList<Order>()));
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btnCancel = new javax.swing.JButton();
        btnSave = new javax.swing.JButton();
        scOrders = new javax.swing.JScrollPane();
        tbOrders = new javax.swing.JTable();
        btnOrdersAdd = new javax.swing.JButton();
        btnOrdersModify = new javax.swing.JButton();
        btnOrdersDelete = new javax.swing.JButton();
        txtPPName = new javax.swing.JTextField();
        lblWhenModified = new javax.swing.JLabel();
        txtWhenModified = new javax.swing.JTextField();
        lblPPName = new javax.swing.JLabel();
        lblOrders = new javax.swing.JLabel();

        setModal(true);
        setResizable(false);

        btnCancel.setText("Cancel");
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });

        btnSave.setText("Save");
        btnSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSaveActionPerformed(evt);
            }
        });

        tbOrders.setAutoCreateRowSorter(true);
        tbOrders.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        scOrders.setViewportView(tbOrders);

        btnOrdersAdd.setText("Add...");
        btnOrdersAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOrdersAddActionPerformed(evt);
            }
        });

        btnOrdersModify.setText("Modify...");
        btnOrdersModify.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOrdersModifyActionPerformed(evt);
            }
        });

        btnOrdersDelete.setText("Delete");
        btnOrdersDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOrdersDeleteActionPerformed(evt);
            }
        });

        lblWhenModified.setText("Last modification date:");

        txtWhenModified.setEditable(false);

        lblPPName.setText("Name:");

        lblOrders.setText("Orders:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(scOrders, javax.swing.GroupLayout.DEFAULT_SIZE, 609, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(btnSave)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnCancel))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(lblOrders)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 312, Short.MAX_VALUE)
                        .addComponent(btnOrdersAdd)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnOrdersModify)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnOrdersDelete))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lblPPName)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(txtPPName, javax.swing.GroupLayout.PREFERRED_SIZE, 172, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(35, 35, 35)
                        .addComponent(lblWhenModified)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(txtWhenModified, javax.swing.GroupLayout.DEFAULT_SIZE, 185, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblPPName)
                    .addComponent(txtPPName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblWhenModified)
                    .addComponent(txtWhenModified, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblOrders)
                    .addComponent(btnOrdersDelete)
                    .addComponent(btnOrdersModify)
                    .addComponent(btnOrdersAdd))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(scOrders, javax.swing.GroupLayout.DEFAULT_SIZE, 469, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnCancel)
                    .addComponent(btnSave))
                .addContainerGap())
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-637)/2, (screenSize.height-619)/2, 637, 619);
    }// </editor-fold>//GEN-END:initComponents

    private void btnOrdersAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOrdersAddActionPerformed
        add = true;
        new FrmOrder(null, factory, this).setVisible(true);
    }//GEN-LAST:event_btnOrdersAddActionPerformed

    private void btnOrdersModifyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOrdersModifyActionPerformed
        index = tbOrders.getSelectedRow();
        add = false;
        if (index >= 0) {
            TMOrder tmo = (TMOrder) tbOrders.getModel();
            Order order = tmo.getOrder(index);
            new FrmOrder(order, factory, this).setVisible(true);
        } else {
            JOptionPane.showMessageDialog(rootPane,
                    "Error:\n Please select an order.",
                    "Error",
                    JOptionPane.ERROR_MESSAGE);
            return;
        }
    }//GEN-LAST:event_btnOrdersModifyActionPerformed

    private void btnOrdersDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOrdersDeleteActionPerformed
        index = tbOrders.getSelectedRow();
        if (index >= 0) {
            int delete = JOptionPane.showConfirmDialog(this,
                    "Are you sure to delete the selected order?",
                    "Confirm your decision",
                    JOptionPane.OK_CANCEL_OPTION,
                    JOptionPane.QUESTION_MESSAGE);
            if (delete == JOptionPane.CANCEL_OPTION) {
                return;
            }
            TMOrder tmo = (TMOrder) tbOrders.getModel();
            tmo.removeOrder(index);
            tbOrders.setModel(tmo);
        } else {
            JOptionPane.showMessageDialog(rootPane,
                    "Error:\n Please select an order.",
                    "Error",
                    JOptionPane.ERROR_MESSAGE);
            return;
        }
    }//GEN-LAST:event_btnOrdersDeleteActionPerformed

    private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
        String planName = txtPPName.getText();
        if (!planName.equals("")) {
            plan = new ProductionPlan(planName);
            List<Order> orders = ((TMOrder) tbOrders.getModel()).getOrders();
            for (Order o : orders) {
                plan.addOrder(o);
            }
            parent.reciveObject(plan);
            this.setVisible(false);
        } else {
            JOptionPane.showMessageDialog(rootPane,
                    "Error:\n Name cannot be empty.",
                    "Error",
                    JOptionPane.ERROR_MESSAGE);
            return;
        }
    }//GEN-LAST:event_btnSaveActionPerformed

    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
        this.setVisible(false);
    }//GEN-LAST:event_btnCancelActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnOrdersAdd;
    private javax.swing.JButton btnOrdersDelete;
    private javax.swing.JButton btnOrdersModify;
    private javax.swing.JButton btnSave;
    private javax.swing.JLabel lblOrders;
    private javax.swing.JLabel lblPPName;
    private javax.swing.JLabel lblWhenModified;
    private javax.swing.JScrollPane scOrders;
    private javax.swing.JTable tbOrders;
    private javax.swing.JTextField txtPPName;
    private javax.swing.JTextField txtWhenModified;
    // End of variables declaration//GEN-END:variables

    public void reciveObject(Object object) {
        Order order = (Order) object;
        TMOrder tmo = (TMOrder) tbOrders.getModel();
        if (add) {
            tmo.addOrder(order);
        } else {
            tmo.setOrder(index, order);
        }
        tbOrders.setModel(tmo);
        tbOrders.tableChanged(new TableModelEvent(tbOrders.getModel()));
    }
}
